package com.hliushi.learn.listener;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @ClassName MyServletRequestListener
 * @Description 使用ServletRequestListener获取用户的访问信息
 * @Author liushi
 * @Date 2021/7/8 15:49
 * @Version V1.0
 **/
@Component
public class MyServletRequestListener implements ServletRequestListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyServletRequestListener.class);


    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        LOGGER.info("session id为: {}", request.getRequestedSessionId());
        LOGGER.info("request line: {} {}/{}", request.getMethod(), request.getRequestURL(),
                StringUtils.isEmpty(request.getQueryString()) ? "" : request.getQueryString()
        );
        // 请求URL中附带的参数
        LOGGER.info("请求URL中附带的参数: {}", request.getQueryString());
        // 请求资源
        LOGGER.info("request uri ----: {}", request.getRequestURI());
        // 请求体 request body
        if ("POST".equals(request.getMethod())) {
            LOGGER.info("request body: ###################");
            Map<String, String[]> bodyMap = request.getParameterMap();
            for (Map.Entry<String, String[]> entry : bodyMap.entrySet()) {
                LOGGER.info("       {} : {}", entry.getKey(), entry.getValue());
            }
        }

        request.setAttribute("name", "hliushi");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        LOGGER.info("request end");
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        LOGGER.info("request域中保存的name值为: {}", request.getAttribute("name"));
    }
}
